import json

from flask import Blueprint, request, redirect, make_response, Response, jsonify

from application.models.model import Course, Tags, course_tag, user_course_chapter, CourseComment
from db_init import db
from swaager_init import siwa
from sqlalchemy import text
from flask_login import current_user

from tools.data_tools import orm2dict, ret_route, limit_offset

course_blue = siwa.blueprint("course", __name__)


@course_blue.route("/", methods=['GET'])
def course_list():
    data = dict(request.args)
    order = request.args.get('order')
    online = int(request.args.get('online_status', 1))
    cate = request.args.get('cate')
    tags = json.loads(request.args.get('tags'))
    limit, offset = limit_offset(data)

    # 首页四个视频
    if not order:
        data = Course.query.order_by(text('-sort_num')).limit(4).all()
        return ret_route(data=orm2dict(data))

    # 基础sql语句
    sql = Course.query.filter_by(online_status=online)

    # 传了 类型的sql
    if cate:
        sql = sql.filter_by(cate=cate)

    # join 表
    data = sql.join(course_tag, course_tag.c.course_id == Course.id) \
        .filter(course_tag.c.tag_id.in_(tags)) \
        .order_by(text(order)) \
        .limit(limit) \
        .offset(offset * limit).all()

    return ret_route(data=orm2dict(data))


@course_blue.route("/<int:course_id>", methods=['GET'])
def course_info(course_id):
    course = Course.query.get(course_id)
    data = orm2dict(course)
    chapters = orm2dict(course.chapters)
    data['chapters'] = chapters
    try:
        user_chapters = db.session.query(user_course_chapter) \
            .filter(user_course_chapter.c.user_id == current_user.id,
                    user_course_chapter.c.chapter_id.in_([i.id for i in course.chapters])) \
            .all()
        data['user_chapters'] = [i[0] for i in user_chapters]

        # 用户看过的所有章节
        # print(current_user.chapters)
        # print(course.chapters)
        # user_chapters = set(i.id for i in current_user.chapters) & set([i.get('id') for i in chapters])
        data['user_chapters'] = list(user_chapters)
    except AttributeError as e:
        data['user_chapters'] = []
    return ret_route(data=data)


@course_blue.route("/<int:course_id>/comment", methods=['GET'])
def course_comment(course_id):
    course = Course.query.get(course_id)
    comments_dict = {comment.id: orm2dict(comment) for comment in course.comments}
    comments = []

    # for comment in comments_dict.values():
    #     # 根评论 添加到最终字典里
    #     if not comment['reply_id']:
    #         comments.append(comment)
    #         continue
    #
    #     # 找到子评论的 父级评论
    #     if not comments_dict[comment['reply_id']].get('son', None):
    #         comments_dict[comment['reply_id']]['son'] = []
    #
    #     comments_dict[comment['reply_id']]['son'].append(comment)

    for comment in comments_dict.values():
        # 根评论 添加到最终字典里
        if not comment['root_id']:
            comment['son'] = []
            comments.append(comment)
            continue

        # 自己修改表结构
        作者 = CourseComment.query.get(comment['reply_id']).zuozhe
        comment['to_user_id'] = 作者.id
        comment['to_user_name'] = 作者.nikename
        comments_dict[comment['root_id']]['son'].append(comment)

    return ret_route(data=comments)



